<template>
    <div id="placard">
        <van-swipe
            @change="onChange"
            :loop="false"
            :show-indicators="false"
            :width="swipeWidth"
        >
            <van-swipe-item v-for="(item, index) in placardList" :key="index">
                <div
                    class="palcard first"
                    :class="{ sacle: current !== index }"
                    @touchstart="onTouchStart"
                    @touchend="onTouchEnd"
                >
                    <img :src="item" alt="" />
                </div>
            </van-swipe-item>
        </van-swipe>
        <div class="tips">
            <span>长按图片保存</span>
        </div>
        <div id="poster" ref="poster" class="poster">
            <img class="bg" :src="posterList[current]" alt="" />
            <img class="qrcode" :src="qrcodeSrc" alt="二维码" />
        </div>
    </div>
</template>

<script>
    import html2canvas from 'html2canvas';
    import QRCode from "qrcode";

    export default {
        props: [], // 父辈向子辈传参
        name: 'placard',
        components: { // 组件的引用

        },
        data() {
            return {
                swipeWidth: 300,
                current: 0,
                placardList: [],
                posterList: [],
                qrcodeSrc: '',
                posterSrc: '',
                flag: [false, false, false]
            }
        },
        methods: {
            onChange(index) {
                this.current = index;
                if (!this.flag[index]) {
                    this.generatePoster(index); // 每次滑动到新图片时生成海报
                }
            },
            updateSwipeWidth() {
                // 计算屏幕宽度的75%
                const screenWidth = window.innerWidth;
                this.swipeWidth = Math.floor(screenWidth * 0.75);
            },
            async generateQrCode(text) {
                const imgSrc = await QRCode.toDataURL(text);
                this.qrcodeSrc = imgSrc;
            },
            generatePoster(index) {
                this.$toast.loading({
                    message: '绘制中...',
                    forbidClick: true,
                });
                // 生成对应图片的海报
                const posterElement = this.$refs.poster;
                // 获取当前设备屏幕的宽度
                const screenWidth = window.innerWidth;
                // 计算调整后的海报尺寸
                const adjustedWidth = Math.floor(screenWidth * 0.675);
                const adjustedHeight = Math.floor(adjustedWidth * 1.779);
                console.log("posterElement", posterElement);
                setTimeout(() => {
                    html2canvas(posterElement, {
                        useCORS: true,
                        allowTaint: true,
                        width: adjustedWidth,
                        height: adjustedHeight
                    }).then((canvas) => {
                        this.posterSrc = canvas.toDataURL('image/png');
                        this.$set(this.placardList, index, this.posterSrc);
                        console.log(this.posterList);
                        this.flag[index] = true
                        this.$toast.clear()
                    });
                }, 1000)
            },
            getPalcard() {
                this.$api.app.getPlacardApi().then(async (res) => {
                    // console.log("海报", res);
                    let arr = this.$utils.func.stringToArray(res.data.img)
                    // console.log("arr", arr);
                    this.placardList = [...arr]
                    this.posterList = [...arr]
                    await this.generateQrCode(res.data.qrcode)
                    this.generatePoster(0)

                }).catch((err) => {
                    this.$toast(err.message)
                });
            },
            onTouchStart() {
                // 开始触摸时启动计时器，模拟长按事件
                this.longPressTimer = setTimeout(this.saveImage, 1000); // 长按时间设定为1秒
            },
            onTouchEnd() {
                // 触摸结束时清除计时器
                clearTimeout(this.longPressTimer);
            },
            saveImage() {
                console.log("保存");
                if (this.flag[this.current]) {
                    let ua = navigator.userAgent.toLowerCase()
                    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                        return 
                    } else {
                        // 非微信环境
                        console.log("普通浏览器");
                        const dataURL = this.placardList[this.current];
                        // console.log("dataUrl",dataURL);
                        var a = document.createElement("a"); // 生成一个a元素
                        var event = new MouseEvent("click"); // 创建一个单击事件
                        a.download = "photo"; // 设置图片名称
                        a.href = dataURL; // 将生成的URL设置为a.href属性
                        a.dispatchEvent(event); // 触发a的单击事件
                    }
                }
            }
        },
        watch: {},
        mounted() {
            this.updateSwipeWidth(); // 初始化宽度
            window.addEventListener('resize', this.updateSwipeWidth); // 监听窗口大小变化

            // this.generatePoster(0); // 初始化加载第一张图片的海报

            this.getPalcard()
        },
        beforeDestroy() {
            window.removeEventListener('resize', this.updateSwipeWidth); // 移除监听器
        }
    }
</script>
    
<style scoped lang='scss'>
    .scroll-view {
        display: flex;
    }
    .van-swipe-item {
        display: flex;
        justify-content: center;
    }
    .palcard {
        margin-top: 51px;
        display: flex;
        justify-content: center;
        & > img {
            width: 253px;
            height: 450px;
            border-radius: 10px 10px 10px 10px;
        }
    }

    .sacle {
        width: 209px !important;
        height: 372px !important;
        margin-top: 90px;
        & > img {
            width: 209px !important;
            height: 372px !important;
        }
    }

    .poster {
        position: fixed;
        z-index: -1000;
        left: 375px;
        .bg {
            width: 253px;
            height: 450px;
        }
        .qrcode {
            width: 112px;
            height: 112px;
            position: absolute;
            top: 60px;
            left: 60px;
        }
    }

    .tips {
        font-weight: 500;
        font-size: 16px;
        color: #f24b3a;
        line-height: 16px;
        padding: 47px 0;
        width: 100%;
        display: flex;
        justify-content: center;
    }
</style>